//
//  BouncedVc.swift
//  Pods
//
//  Created by eme on 2017/4/7.
//
//

import UIKit
import UtilCore
import RickonCore

class BouncedVc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var custom_TableView: UITableView!
    
    @IBOutlet weak var sheetView: UIView!
    
    @IBOutlet weak var dimBackgroundView: UIView!
    
    @IBOutlet weak var eventButton: UIButton!           //事件按钮
    
    @IBOutlet weak var titleLabel: UILabel!             //主标题
    
    @IBOutlet weak var subtitle_Label: UILabel!         //副标题
    
    @IBOutlet weak var cancleButton: UIButton!          //取消按钮
    
    var contentModelArr:[PayArrayModel]?{
        didSet{
//            self.custom_TableView.reloadData()
        }
    }
    
    var payid:String?                                   //支付ID
    
    var type:String?                                    //取消还是付款
    
    var CancelVm:CancelOrderVm?                         //取消订单ViewModel
    
    var titletype:String?                               //类型
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    
    
    /****************************Storyboard 绑定方法区域****************************/
    @IBAction func dismiss(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }
    @IBAction func cancle(_ sender: AnyObject) {
        self.dismiss(animated: true, completion: nil)
    }
    @IBAction func eventClicked(_ sender: UIButton) {
        if type == "fk"{
            
            self.dismiss(animated: true, completion: {
                
                if let modelArr = self.contentModelArr{
                    _ = "pay".openURL(["orderid":"","ordersumamount":modelArr[0].totalorderamount.getPriceStr(),"payid":self.payid ?? "","ordertype":"OS"])
                }
            })
            
        }else if type == "qx"{
            self.CancelVm?.cancelOrder.onNext(self.payid ?? "")
        }
        
    }
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        self.modalTransitionStyle = .coverVertical
        self.modalPresentationStyle = .custom
        self.transitioningDelegate = self
        dimBackgroundView.backgroundColor = UIColor (white: 0, alpha: 0.4)
        dimBackgroundView.alpha = 0
        titleLabel.normal_fontSize(17)
        subtitle_Label.normal_fontSize(15)
        eventButton.titleLabel?.normal_fontSize(15)
        cancleButton.titleLabel?.normal_fontSize(15)
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.setUpTableView()
        self.setUp()
    }
    func setUpTableView(){
        self.custom_TableView.showsVerticalScrollIndicator = false
        self.custom_TableView.delegate = self
        self.custom_TableView.dataSource = self
    }
    func setUp(){
        if type == "qx"{
            self.eventButton.setTitle("确定", for: .normal)
        }else{
            self.eventButton.setTitle("付款", for: .normal)
        }
        self.titleLabel.text = "以下订单需一起\(self.titletype ?? "")"
        self.subtitle_Label.text = "由于以下订单共享优惠，需要一起\(self.titletype ?? "")"
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
        //取消订单
        self.CancelVm = CancelOrderVm()
        
        self.CancelVm?.backDate.asObserver().subscribe(onNext:{ result in
            
            if result == true{
                
                self.dismiss(animated: true, completion: {
                    
                    NotificationCenter.default.post(name: .WXPaysuccess, object: nil)
                })
                
            }
            
        }).addDisposableTo(disposeBag)
        
        self.CancelVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
    }
}
extension Notification.Name{
    static let WXPaysuccess = Notification.Name("WXPaysuccess")
}
extension BouncedVc:UIViewControllerTransitioningDelegate{
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return Custom_presentAnimated()
    }
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return Custom_dismissAnimated()
    }
}
class Custom_presentAnimated : NSObject,UIViewControllerAnimatedTransitioning{
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.5
    }
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
        let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as! BouncedVc
        let containerView = transitionContext.containerView
        // start animation status
        toVC.dimBackgroundView.alpha = 0
        toVC.sheetView.frame = CGRect (x: fromVC.view.frame.origin.x,
                                       y: fromVC.view.frame.size.height,
                                       width: fromVC.view.frame.size.width,
                                       height: fromVC.view.frame.size.height)
        containerView.addSubview(toVC.view)
        let duration: TimeInterval = transitionDuration(using: transitionContext)
        // 执行动画
        UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.0, options: .curveLinear, animations: {
            toVC.dimBackgroundView.alpha = 1
            toVC.sheetView.frame = transitionContext.finalFrame(for: toVC)
        }, completion: { (finished) in
            transitionContext.completeTransition(true)
        })
    }
}
class Custom_dismissAnimated:NSObject,UIViewControllerAnimatedTransitioning{
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.5
    }
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as! BouncedVc
        fromVC.dimBackgroundView.alpha = 1
        let duration: TimeInterval = transitionDuration(using: transitionContext)
        let finalY:CGFloat = fromVC.view.frame.size.height
        UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.0, options: .curveLinear, animations: {
            fromVC.dimBackgroundView.alpha = 0
            fromVC.sheetView.frame.origin.y += finalY
        }, completion: { finish in
            transitionContext.completeTransition(true)
        })
        
    }
}
extension BouncedVc:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let modelArr = self.contentModelArr{
            return modelArr.count
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! EventTableViewCell
        cell.item = self.contentModelArr![indexPath.row]
        return cell
    }
}
